package cn.jisol.ngame.listener;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassUtil;
import cn.jisol.ngame.actions.core.NAction;
import cn.jisol.ngame.actions.core.NActionMethod;
import cn.jisol.ngame.network.JNetwork;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Component
public class InitNGameRPCListener {

    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("--- 初始化 --- NGame Action ---");

        Set<Class<?>> classes = this.getScanPackage();

        classes.forEach((Class<?> value) -> {
            if(Objects.nonNull(AnnotationUtil.getAnnotation(value, NAction.class))){
                for (Method method : value.getMethods()){
                    NActionMethod nActionMethod;
                    if (Objects.nonNull(nActionMethod = AnnotationUtils.findAnnotation(method, NActionMethod.class))){
                        List<Method> methods = JNetwork.AllAction.get(nActionMethod.value());
                        if (Objects.isNull(methods)){
                            JNetwork.AllAction.put(nActionMethod.value(),new ArrayList<Method>(){
                                {
                                    add(method);
                                }
                            });
                        }else{
                            methods.add(method);
                        }
                    }
                }
            }
        });

        System.out.println("NGame Action 数量:"+JNetwork.AllAction.size());

    }

    public Set<Class<?>> getScanPackage(){
        return ClassUtil.scanPackage("");
    }
}
